package cn.schoolwow.ams.module.initial.controller;

import cn.schoolwow.ams.domain.option.QuickAMSOption;
import cn.schoolwow.ams.module.initial.domain.InitialAMSContext;
import cn.schoolwow.ams.module.initial.service.GetAppPackJavaScriptFlow;
import cn.schoolwow.ams.module.initial.service.InitialAMSContextCompositeBusiness;
import cn.schoolwow.quickflow.QuickFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/ams")
public class AMSInitialController {
    @Autowired
    private QuickFlow amsFlow;

    @Autowired
    private QuickAMSOption quickAMSOption;

    @RequestMapping("/initial")
    public InitialAMSContext initial() {
        FlowContext flowContext = amsFlow.executeFlow(new InitialAMSContextCompositeBusiness());
        InitialAMSContext initialAMSContext = flowContext.checkInstanceData(InitialAMSContext.class);
        initialAMSContext.debug = quickAMSOption.debug;
        return initialAMSContext;
    }

    @RequestMapping(value = "/getAppPackJavaScript", produces = "text/javascript;charset=UTF-8")
    public ResponseEntity<StreamingResponseBody> getAppPackJavaScript() {
        FlowContext flowContext = amsFlow.executeFlow(new GetAppPackJavaScriptFlow());
        String appPackJavaScript = (String) flowContext.checkData("appPackJavaScript");

        StreamingResponseBody responseBody = outputStream -> {
            outputStream.write(appPackJavaScript.getBytes(StandardCharsets.UTF_8));
        };

        return ResponseEntity.ok()
                .contentType(MediaType.valueOf("text/javascript"))
                .body(responseBody);
    }

}
